# -*- coding: UTF-8 -*-
import time
import os
import requests
import urllib3
import inspect

from tools.handle_path import config_path
from pyLib.YamlManage import YamlReader
from tools.Initialization import DEEPFOS_HOST, ACCOUNT_HOST
from tools.GetEdition import EDITION


class BaseAPI:

    def __init__(
            self,
            headers: dict = None,
            version: str = "1.0"
    ):
        """
        :param version: 组件服务版本号
        :param headers: 请求头
        """
        self._data = YamlReader(os.path.join(config_path, 'apiConfig.yaml')).get_yaml_data()[self.__class__.__name__]
        self.url = f"{DEEPFOS_HOST}/deepfos-server/"
        # 接口完整地址
        self.api_url = None
        server_path = self._data.get("server_path")
        module_type = self._data.get("module_type")
        # 配置了服务地址
        if server_path:
            self.url += server_path
        # 根据组件版本
        elif module_type:
            # 组件服务
            module_server = EDITION.get_edition(self._data["module_type"], version)
            self.url += module_server
        # 账户中心
        else:
            self.url = ACCOUNT_HOST
        self.headers = headers

    def request_send(
            self,
            params=None,
            data=None,
            json=None,
            files=None,
            headers=None,
            verify=False,
            timeout=30000,
            auth=None,
            uri=None
    ):
        urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        # 调用者的函数名
        method_name = inspect.stack()[1][3]
        # 请求地址，请求方法
        path, method = self._data[method_name].values()
        self.api_url = f"{self.url}{path}/{uri}" if uri else f"{self.url}{path}"
        r = requests.request(
            method=method,
            url=self.api_url,
            params=params,
            data=data,
            json=json,
            headers=headers if headers else self.headers,
            timeout=timeout,
            files=files,
            verify=verify,
            auth=auth
        )
        return r

    def git_version(self):
        self.api_url = f"{self.url}/git-version"
        r = requests.get(url=self.api_url, verify=False)
        if r.status_code == 200:
            return True
        return False


class RetryConnection(object):
    """
    请求重试机制
    frequency: 重试次数
    """

    def __init__(self, frequency: int = 3):
        self.frequency = frequency

    def __call__(self, func):
        def wrapper(*args, **kwargs):
            c = 0
            for i in range(1, self.frequency + 1):
                try:
                    return func(*args, **kwargs)
                except Exception as e:
                    c += 1
                    print(f"wait retry connection!  --------------------------------- {i}")
                    print(time.localtime())
                    time.sleep(10)
                    if self.frequency == c:
                        print("Maximum number of retries reached............................")
                        return e

        return wrapper


@RetryConnection(frequency=3)
def request_general(method, url, params=None, data=None, headers=None, json=None, verify=False, files=None,
                    timeout=30000, auth=None):
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    r = requests.request(verify=verify, method=method, url=url, params=params, data=data, json=json,
                         headers=headers, timeout=timeout, files=files, auth=auth)
    return r


def get_all_module_id(modules_list=None):
    """
    获取所有存在的组件ID
    :param modules_list: 查询组件ID返回的json串
    :return: list
    """
    mod_list = []
    for mod_list_ in modules_list.get("data"):
        mod_list.append(mod_list_.get("moduleId"))
    return mod_list
